import React, { PureComponent } from 'react';
import router from 'umi/router';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Row, Modal, Select, Steps, Button, Radio, Col } from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; // 引入头部组件
import HOCSelect from '@/components/AntDesign/Select';
import styles from '@/utils/utils.less';
import AddEmpForm from '../../SocialService/SocialCard/AddEmpForm';
import AddEmpInfor from '../../SocialService/SocialCard/AddEmpInfor';
import AddMatInfor from '../../SocialService/SocialCard/AddMatInfor';

const { confirm } = Modal;
const FormItem = Form.Item;
const { Step } = Steps;
const { Option } = Select;
const steps = [
  {
    title: '查询员工',
    content: 'First-content',
  },
  {
    title: '发起办理',
    content: 'Second-content',
  },
];
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 9,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
    md: { span: 7 },
  },
};
const formItemLayouts = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
    xl: { span: 8 },
    xxl: { span: 6 },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
  },
};
const RadioGroup = Radio.Group;
@connect(
  ({
    publicdata: { serviceTypeList },
    archservicehandle: {
      sendData,
      empNameList,
      empNameSelect,
      elementArr,
      matFileDictItem,
      coltFlag,
    },
    loading,
  }) => ({
    // 对应的文件名：{方法名}
    sendData,
    empNameList,
    empNameSelect,
    serviceTypeList,
    matFileDictItem,
    elementArr,
    coltFlag,
    loading: loading.effects['archservicehandle/fetchEmpNameList'],
  })
)
class CardAdd extends PureComponent {
  state = {
    current: 0,
    btnDis: true,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'archservicehandle/clearEmpName',
      payload: [],
    });
    dispatch({
      type: 'publicdata/serviceType',
      payload: { serType: 3 },
    });
  }

  handleCancel = () => {};

  // 下一步
  prev = () => {
    const { current } = this.state;
    const currentStep = current - 1;
    this.setState({ current: currentStep, btnDis: true });
    const { dispatch } = this.props;
    dispatch({
      type: 'archservicehandle/clearEmpName',
      payload: {},
    });
  };

  // 服务类型
  serviceType = value => {
    this.setState({
      serTypeId: value.key,
    });
  };

  // 提交运行
  saveUpdate = () => {
    const {
      location: { pathname },
      form,
    } = this.props;
    const tempUrl = pathname.split('/add')[0];
    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        const matlist = [];
        const rcrdSerHdl = {};
        const newValues = values;
        Object.keys(values).forEach(key => {
          if (key.indexOf('_') !== -1) {
            if (String(values[key].inpType) === '9') {
              let file = '';
              if (values[key].fileList && values[key].fileList.length) {
                values[key].fileList.map(item => {
                  if (item.response && item.response.success) {
                    file += `${item.response.data},`;
                  }
                  return true;
                });
                newValues[key].inpVal = file ? file.slice(0, file.length - 1) : '';
              }
            }
            newValues[key].pkgPageDetailId = values[key].pageDetailId;
            matlist.push(values[key]);
          } else if (key === 'matFlag') {
            rcrdSerHdl.matFlag = values[key];
          } else if (key === 'copyFiles') {
            rcrdSerHdl.copyFiles = values[key];
          } else if (key === 'masterFiles') {
            rcrdSerHdl.masterFiles = values[key];
          }
        });
        const { dispatch, empNameSelect } = this.props;
        const { serTypeId } = this.state;
        rcrdSerHdl.sendId = empNameSelect[0].sendId;
        rcrdSerHdl.source = empNameSelect[0].dataSource;
        rcrdSerHdl.serTypeId = serTypeId;
        rcrdSerHdl.submitFlag = '1';
        const param = {
          matlist,
          rcrdSerHdl,
        };

        dispatch({
          type: 'archservicehandle/addCheckList',
          payload: param,
          callback: response => {
            if (response) {
              if (String(response.data.code) === '201') {
                message.error('该员工正在办理此服务类型，不能新增！');
              } else if (String(response.data.code) === '202') {
                confirm({
                  content: '当前人员已办理过此项业务，确定再次办理?',
                  okText: '确定',
                  cancelText: '取消',
                  onOk() {
                    dispatch({
                      type: 'archservicehandle/addList',
                      payload: param,
                      callback: res => {
                        if (res.success) {
                          router.push(`${tempUrl}/index`);
                        }
                      },
                    });
                  },
                  onCancel() {},
                });
              } else if (String(response.data.code) === '200') {
                router.push(`${tempUrl}/index`);
              }
            }
          },
        });
      }
    });
  };

  // 提交数据
  save = () => {
    const { location, form } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/add')[0];
    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        const matlist = [];
        const rcrdSerHdl = {};
        const newValues = values;
        Object.keys(values).forEach(key => {
          if (key.indexOf('_') !== -1) {
            if (String(values[key].inpType) === '9') {
              let file = '';
              if (values[key].inpVal) {
                file += `${values[key].inpVal},`;
              }
              if (values[key].fileList && values[key].fileList.length) {
                values[key].fileList.map(item => {
                  if (item.response && item.response.success) {
                    file += `${item.response.data},`;
                  }
                  return true;
                });
                newValues[key].inpVal = file ? file.slice(0, file.length - 1) : '';
              }
            }
            newValues[key].pkgPageDetailId = values[key].pageDetailId;
            matlist.push(newValues[key]);
          } else if (key === 'matFlag') {
            rcrdSerHdl.matFlag = values[key];
          } else if (key === 'copyFiles') {
            rcrdSerHdl.copyFiles = values[key];
          } else if (key === 'masterFiles') {
            rcrdSerHdl.masterFiles = values[key];
          }
        });
        const { dispatch, empNameSelect } = this.props;
        const { serTypeId } = this.state;
        rcrdSerHdl.sendId = empNameSelect[0].sendId;
        rcrdSerHdl.source = empNameSelect[0].dataSource;
        rcrdSerHdl.serTypeId = serTypeId;
        rcrdSerHdl.submitFlag = '2';
        const param = {
          matlist,
          rcrdSerHdl,
        };
        dispatch({
          type: 'archservicehandle/addCheckList',
          payload: param,
          callback: response => {
            if (response) {
              if (String(response.data.code) === '201') {
                message.error('该员工正在办理此服务类型，不能新增！');
              } else if (String(response.data.code) === '202') {
                confirm({
                  content: '当前人员已办理过此项业务，确定再次办理?',
                  okText: '确定',
                  cancelText: '取消',
                  onOk() {
                    dispatch({
                      type: 'archservicehandle/addList',
                      payload: param,
                      callback: res => {
                        if (res.success) {
                          router.push(`${tempUrl}/index`);
                        }
                      },
                    });
                  },
                  onCancel() {},
                });
              } else if (String(response.data.code) === '200') {
                router.push(`${tempUrl}/index`);
              }
            }
          },
        });
      }
    });
  };

  // 选择材料
  onSelectData = element => {
    const { elementArr, dispatch } = this.props;
    dispatch({
      type: 'archservicehandle/matInfor',
      payload: { elementArr, element },
    });
  };

  // 选择员工
  empData = (data, flag) => {
    const { dispatch } = this.props;
    this.setState({
      btnDis: flag,
    });
    dispatch({
      type: 'archservicehandle/fetchEmpName',
      payload: data,
    });
  };

  // 查询员工
  empSearch = values => {
    const { dispatch } = this.props;
    dispatch({
      type: 'archservicehandle/fetchEmpNameList',
      payload: values,
    });
  };

  // 证件号校验
  idVailFunc = values => {
    const { dispatch } = this.props;
    if (values) {
      dispatch({
        type: 'archservicehandle/fetchEmpNoList',
        payload: values,
        callback: res => {
          this.setState({
            btnDis: res,
          });
        },
      });
    }
  };

  // 下一步
  next = () => {
    const { dispatch, empNameSelect, form } = this.props;
    const { current, serTypeId } = this.state;
    form.validateFieldsAndScroll({ force: true }, err => {
      if (err) return;
      this.setState({ current: current + 1 });
      const parameterMat = {
        serType: 3,
        serTypeId,
        areaId: empNameSelect[0].areaId,
      };

      dispatch({
        type: 'archservicehandle/fetchMatList',
        payload: parameterMat,
      });
      const parameter = {
        sendId: empNameSelect[0].sendId,
        dataSource: empNameSelect[0].dataSource,
      };
      dispatch({
        type: 'archservicehandle/fetchSendInfor',
        payload: parameter,
      });
    });
  };

  close = () => {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/add')[0];
    router.push(`${tempUrl}/index`);
  };

  // 材料校验
  checkElement = (rule, value, callback) => {
    let tip = '';
    switch (Number(value.inpType)) {
      case 1:
        tip = `请输入不超过30个字的${value.matName}`;
        break;
      case 9:
        tip = `请上传${value.matName}`;
        break;
      case 3:
        tip = `请输入不超过300个字的${value.matName}`;
        break;
      default:
        tip = `请选择${value.matName}`;
        break;
    }
    if (
      +value.inpType !== 9
        ? rule.required && !value.inpVal
        : rule.required && !(value.fileList && value.fileList.length)
    ) {
      callback(tip);
    } else if (+value.inpType === 1 || +value.inpType === 3) {
      if (rule.max < (value.inpVal && value.inpVal.length)) {
        callback(tip);
      } else {
        callback();
      }
    } else {
      callback();
    }
  };

  render() {
    const { current, btnDis } = this.state;
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const {
      elementArr,
      matFileDictItem,
      sendData,
      serviceTypeList,
      empNameList,
      empNameSelect,
      coltFlag,
      loading,
    } = this.props;
    const { empSendInfoVo, empBaseInfoVo } = sendData;
    const max = val => {
      if (val === 1) return 30;
      if (val === 3) return 300;
      return null;
    };
    const renderElem = elementArrs =>
      elementArrs && elementArr.length ? (
        elementArrs.map(element => (
          <Row key={element.pageDetailId}>
            <Col span={16}>
              <FormItem {...formItemLayouts} label={<span> {element.matName}</span>}>
                {getFieldDecorator(`mat_${element.pageDetailId}`, {
                  rules: [
                    {
                      required: +element.reqFlag === 1,
                      validator: this.checkElement,

                      max: max(+element.inpType),
                    },
                  ],
                  initialValue: element,
                })(<AddMatInfor onChange={this.onSelectData} />)}
              </FormItem>
            </Col>{' '}
          </Row>
        ))
      ) : (
        <div />
      );
    return (
      <PageHeaderWrapper>
        <Card style={{ marginBottom: 12, marginTop: 10 }}>
          <Steps current={current} style={{ width: 327, margin: '0 auto' }}>
            {steps.map(item => (
              <Step key={item.title} title={item.title} />
            ))}
          </Steps>
        </Card>
        <div className={styles.stepsAction}>
          {current === 0 && (
            <Card>
              <FormItem {...formItemLayout} label={<span>服务类型</span>}>
                {getFieldDecorator('serTypeId', {
                  rules: [
                    {
                      required: true,
                      message: '请选择服务类型',
                    },
                  ],
                })(
                  <HOCSelect
                    style={{ width: '100%' }}
                    placeholder="请选择服务类型"
                    labelInValue
                    showSearch
                    onChange={this.serviceType}
                  >
                    {serviceTypeList &&
                      serviceTypeList.length &&
                      serviceTypeList.map(options => (
                        <Option key={options.serTypeId}>{options.serTypeIdName}</Option>
                      ))}
                  </HOCSelect>
                )}
              </FormItem>
              <AddEmpForm
                empNameList={empNameList}
                empNameSelect={empNameSelect}
                onSearch={this.empSearch}
                empData={this.empData}
                idVailFunc={this.idVailFunc}
                loading={loading}
              />
              <Row style={{ textAlign: 'center', justifyContent: 'center' }}>
                <Button onClick={this.close}>关闭</Button>
                <Button
                  style={{ marginLeft: 30 }}
                  type="primary"
                  onClick={() => this.next()}
                  disabled={btnDis}
                >
                  下一步
                </Button>
              </Row>
            </Card>
          )}
          {current === 1 && (
            <div>
              <div>
                <AddEmpInfor
                  empSendInfoVo={empSendInfoVo}
                  empBaseInfoVo={empBaseInfoVo}
                  loading={loading}
                />
                <Card>
                  {String(coltFlag) === '1' && (
                    <Card>
                      <Form>
                        <div>
                          {matFileDictItem && matFileDictItem.length ? (
                            <div>
                              <Row>
                                <Col span={16}>
                                  <FormItem {...formItemLayouts} label="原件材料:">
                                    {getFieldDecorator('masterFiles', {
                                      rules: [
                                        {
                                          required: false,
                                          message: '请选择原件材料',
                                        },
                                      ],
                                    })(
                                      <HOCSelect
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择原件材料"
                                        onChange={this.aaa}
                                      >
                                        {matFileDictItem &&
                                          matFileDictItem.length &&
                                          matFileDictItem.map(options => (
                                            <Option key={options.itemCode}>
                                              {options.itemName}
                                            </Option>
                                          ))}
                                      </HOCSelect>
                                    )}
                                  </FormItem>
                                </Col>
                              </Row>
                              <Row>
                                <Col span={16}>
                                  <FormItem {...formItemLayouts} label="复印件材料:">
                                    {getFieldDecorator('copyFiles', {
                                      rules: [
                                        {
                                          required: false,
                                          message: '请选择复印件材料',
                                        },
                                      ],
                                    })(
                                      <HOCSelect
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择复印件材料"
                                      >
                                        {matFileDictItem &&
                                          matFileDictItem.length &&
                                          matFileDictItem.map(options => (
                                            <Option key={options.itemCode}>
                                              {options.itemName}
                                            </Option>
                                          ))}
                                      </HOCSelect>
                                    )}
                                  </FormItem>
                                </Col>
                              </Row>
                            </div>
                          ) : null}
                          {renderElem(elementArr)}
                          <Row>
                            <Col span={14} offset={1}>
                              <FormItem {...formItemLayouts} label="材料是否完整:">
                                {getFieldDecorator('matFlag', {
                                  rules: [
                                    {
                                      required: true,
                                      message: '请选择材料是否完整',
                                    },
                                  ],
                                })(
                                  <RadioGroup>
                                    <Radio value="1">是</Radio>
                                    <Radio value="2">否</Radio>
                                  </RadioGroup>
                                )}
                              </FormItem>
                            </Col>
                          </Row>
                        </div>
                      </Form>
                    </Card>
                  )}
                  <Row style={{ textAlign: 'center', justifyContent: 'center' }}>
                    <Button onClick={this.close}>关闭</Button>
                    <Button style={{ marginLeft: 16 }} onClick={() => this.prev()}>
                      上一步
                    </Button>
                    <Button style={{ marginLeft: 16 }} type="primary" onClick={() => this.save()}>
                      保存
                    </Button>
                    <Button
                      style={{ marginLeft: 16 }}
                      type="primary"
                      onClick={() => this.saveUpdate()}
                    >
                      保存并提交运行
                    </Button>
                  </Row>
                </Card>
              </div>
            </div>
          )}
        </div>
      </PageHeaderWrapper>
    );
  }
}
const CardAddform = Form.create()(CardAdd);
export default CardAddform;
